package com.zimin.common.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zimin.common.constant.ServletConstant;

import java.util.HashMap;

/**
 * @Author: 嘉阳
 * @Date: 2020/12/6
 * @Describe: Ip 工具类
 */
public class IpUtil {

    /**
     * 地理位置
     *
     * @param ip IP地址
     */
    public static String getAddressByIp(String ip) {
        if (!ServletConstant.DEFAULT_IP.equals(ip)) {
            HashMap<String, Object> paramMap = new HashMap<>(2);
            paramMap.put(IP, ip);
            paramMap.put(JSON, Boolean.TRUE);
            String result = HttpUtil.get(IP_URL, paramMap);
            if (StrUtil.isNotBlank(result)) {
                JSONObject jsonObject = JSONUtil.toBean(result, JSONObject.class);
                String pro = Convert.toStr(jsonObject.get(PRO));
                String city = Convert.toStr(jsonObject.get(CITY));
                if (StrUtil.isAllNotBlank(pro, city)) {
                    return StrUtil.format("{} {} ", pro, city);
                }
            }
        }
        return DEFAULT_ADDRESS;
    }

    public static void main(String[] args) {
        System.out.println(getAddressByIp("49.233.31.27"));
    }

    private static final String DEFAULT_ADDRESS = "局域网";

    private static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    private static final String IP = "ip";

    private static final String JSON = "json";

    private static final String PRO = "pro";

    private static final String CITY = "city";

}
